<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :lg="6" :md="6" :sm="6">
            <a-form-item label="产品代码">
              <a-input v-model="queryParam.materialCode" placeholder="请输入产品代码"></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="6" :sm="6">
            <a-form-item label="产品名称">
              <a-input v-model="queryParam.materialName" placeholder="请输入产品名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="价格编号">
              <a-input v-model="queryParam.serial" placeholder="请输入价格编号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="6" :sm="6">
            <a-form-item label="供应商">
              <j-search-select-tag
                v-model="queryParam.supplierId"
                dict="hf_supplier,name,id"
                placeholder="请选择供应商"
                type="list"
                @change="searchQuery"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="6" :sm="6">
            <a-form-item label="供应商品番">
              <a-input v-model="queryParam.purchaseCode" placeholder="请输入供应商品番"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="6">
            <a-form-item label="简号">
              <a-input v-model="queryParam.purchaseCode1" placeholder="请输入简号"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-row>
        <a-button icon="search" type="primary" @click="searchQuery">查询</a-button>
        <a-button icon="reload" type="primary" @click="searchReset">重置</a-button>
        <a-button icon="plus" type="primary" @click="handleAdd">新增</a-button>
        <a-button icon="plus" type="primary" @click="handleOpenBatchAdd">
          批量添加
        </a-button>
      </a-row>
      <a-row>
        <a-button
          v-has="'purchasePrice:import'"
          icon="download"
          type="primary"
          @click="handleExportXlsTemplate('采购价格导入模板')"
          >引出导入模板
        </a-button>
        <a-button icon="download" type="primary" @click="handleExportXls('采购价格方案')">导出当前所有数据</a-button>
        <a-upload
          v-has="'purchasePrice:import'"
          :action="importExcelUrl"
          :headers="tokenHeader"
          :multiple="false"
          :showUploadList="false"
          name="file"
          @change="handleImportExcel"
        >
          <a-button icon="import" type="primary">导入</a-button>
        </a-upload>
        <a-button
          v-has="'purchasePrice:inputSupplier'"
          :loading="inputSupplier.loading"
          icon="diff"
          type="primary"
          @click="handleAutoInputCustom"
          >更新无供应商的记录
        </a-button>
        <a-button
          icon="import"
          style="background: #FF8F00;border: #FF8F00;"
          type="primary"
          @click="uploadModel.openUpload = true"
          >金蝶导入
        </a-button>
        <a-modal :footer="false" :visible="uploadModel.openUpload" @cancel="uploadModel.openUpload = false">
          <a-spin :spinning="uploadModel.uploadLoading">
            <a-form :labelCol="{ span: 4 }" :wrapperCol="{ span: 16 }">
              <a-row>
                <a-col :span="24">
                  <a-form-item label="税率">
                    <a-input v-model="uploadModel.tax" placeholder="请输入税率"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="选择文件">
                    <a-upload :customRequest="customUpload" :multiple="false" :showUploadList="false" name="file">
                      <a-button icon="import" style="background: #FF8F00;border: #FF8F00;" type="primary">
                        选择金蝶导出的文件
                      </a-button>
                    </a-upload>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-spin>
        </a-modal>

        <a-button icon="search" type="primary" @click="handleTax">一键更改所有税率</a-button>
        <a-tooltip>
          <template slot="title">
            <span>请先选择在【客户名称】中选择客户</span>
          </template>
          <a-upload
            :action="importFileUrl"
            :customRequest="priceFileCustomUpload"
            :headers="tokenHeader"
            :multiple="true"
            :show-upload-list="false"
            name="file"
          >
            <a-button type="primary">
              <a-icon type="upload" />
              上传价格协议
            </a-button>
          </a-upload>
        </a-tooltip>
      </a-row>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pagination="ipagination"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: true }"
        bordered
        class="j-table-force-nowrap"
        rowKey="id"
        size="middle"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleHistory(record)">历史价格</a>
          <a-divider type="vertical" />
          <a @click="handleDelete(record.id)">删除</a>
        </span>

        <span slot="fileSlot" slot-scope="text, record">
          <div v-if="record.priceFile && Object.keys(record.priceFile).length !== 0">
            <a-popover placement="leftBottom" trigger="click">
              <div v-for="(item, index) in record.priceFile" :key="index" slot="content" style="margin-bottom: 5px">
                <a-tooltip>
                  <span slot="title">点击即可打开</span>
                  <a @click="previewFile(item)">价格协议{{ index }}</a>
                </a-tooltip>
                <a-button style="margin-right: 5px;margin-left: 5px" type="primary" @click="downloadFile(item)"
                  >下载</a-button
                >
                <a-button type="primary" @click="deleteUploadedFile(item, index, record.id)">删除</a-button>
              </div>
              <a-button type="primary">附件</a-button>
            </a-popover>
          </div>
          <div v-else>
            无内容
          </div>
        </span>
      </a-table>
    </div>

    <HfPurchasePriceModal ref="modalForm" @ok="modalFormOk"></HfPurchasePriceModal>
    <HfPurchasePriceHistoryModal ref="HfPurchasepriceHistoryModal"></HfPurchasePriceHistoryModal>
    <HandlePurchaseTaxModal ref="HandlePurchaseTaxModal"></HandlePurchaseTaxModal>
    <HfBatchAddPurchasePrice ref="HfBatchAddPurchasePriceRef" @ok="handleBatchAddOk" />
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HfPurchasePriceModal from './modules/HfPurchasePriceModal.vue'
import HfPurchasePriceHistoryModal from './modules/HfPurchasepriceHistoryModal'
import HandlePurchaseTaxModal from '@views/purchase/modules/HandlePurchaseTaxModal.vue'
import { deleteAction, getAction, postAction } from '@api/manage'
import { Modal } from 'ant-design-vue'
import HfBatchAddPurchasePriceList from '@views/purchase/modules/HfBatchAddPurchasePriceList.vue'
import HfBatchAddPurchasePrice from '@views/purchase/modules/HfBatchAddPurchasePrice.vue'

export default {
  name: 'HfPurchasePriceList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    HfBatchAddPurchasePrice,
    HfBatchAddPurchasePriceList,
    HandlePurchaseTaxModal,
    HfPurchasePriceModal,
    HfPurchasePriceHistoryModal
  },
  data() {
    return {
      description: '采购价格方案管理页面',
      uploadModel: {
        openUpload: false,
        uploadLoading: false,
        tax: 13
      },
      inputSupplier: {
        loading: false
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '价格编号',
          align: 'center',
          dataIndex: 'serial'
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode'
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '未税单价',
          align: 'center',
          dataIndex: 'price',
          customRender: function(t) {
            return (t = '￥' + t)
          }
        },
        {
          title: '含税单价',
          align: 'center',
          dataIndex: 'taxPrice',
          customRender: function(t, r, index) {
            return (t = '￥' + t)
          }
        },
        {
          title: '税率',
          align: 'center',
          dataIndex: 'tax',
          customRender: function(t, r, index) {
            return (t += '%')
          }
        },
        {
          title: '供应商名称',
          align: 'center',
          dataIndex: 'supplierId_dictText'
        },
        {
          title: '供应商品番',
          align: 'center',
          dataIndex: 'purchaseCode'
        },
        {
          title: '简号',
          align: 'center',
          dataIndex: 'purchaseCode1'
        },
        {
          title: 'QAD',
          align: 'center',
          dataIndex: 'qad'
        },
        {
          title: '执行时间',
          align: 'center',
          dataIndex: 'useTime'
        },
        {
          title: '附件',
          align: 'center',
          dataIndex: 'priceFile',
          scopedSlots: { customRender: 'fileSlot' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/purchase/hfPurchasePrice/list',
        delete: '/purchase/hfPurchasePrice/delete',
        deleteBatch: '/purchase/hfPurchasePrice/deleteBatch',
        exportXlsUrl: '/purchase/hfPurchasePrice/exportXls',
        exportXlsTemplateUrl: '/purchase/hfPurchasePrice/exportXlsTemplate',
        importExcelUrl: 'purchase/hfPurchasePrice/importExcelByJD',
        importFileUrl: '/purchase/hfPurchasePrice/importFile',
        deleteUploadedFileUrl: '/purchase/hfPurchasePrice/deleteUploadedFile',
        autoInputCustomUrl: '/purchase/hfPurchasePrice/autoInputCustom'
      },
      dictOptions: {},
      superFieldList: []
    }
  },
  created() {},
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    importFileUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importFileUrl}`
    },
    selectedPriceIds: function() {
      let ids = ''
      if (this.selectedRowKeys.length > 0) {
        ids = this.selectedRowKeys.join(',')
      }
      return ids
    }
  },
  methods: {
    customUpload(options) {
      this.uploadModel.uploadLoading = true
      let { file } = options
      const formData = new FormData()
      formData.append('file', file)
      formData.append('tax', this.uploadModel.tax)
      postAction(this.importExcelUrl, formData, { headers: this.tokenHeader, timeout: 0 })
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .catch(err => {
          console.log('err', err)
        })
        .finally(() => {
          this.uploadModel.openUpload = false
          this.uploadModel.uploadLoading = false
        })
    },
    priceFileCustomUpload(options) {
      let { file } = options
      // 文件名后缀
      const fileSuffix = file.name.slice(file.name.indexOf('.') + 1)

      if (fileSuffix !== 'pdf') {
        this.$message.error('文件不是PDF！请选择PDF文件')
        return
      }
      if (!this.queryParam.supplierId) {
        this.$message.error('请先选择供应商')
        return
      }
      if (this.selectedPriceIds.length === 0) {
        this.$message.error('请至少选择一条物料')
        return
      }
      this.loading = true
      const formData = new FormData()
      formData.append('file', file)
      formData.append('supplierId', this.queryParam.supplierId)
      formData.append('priceIds', this.selectedPriceIds)
      postAction(this.importFileUrl, formData, { headers: this.tokenHeader, timeout: 0 })
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .catch(err => {
          console.log('err', err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleHistory(record) {
      this.$refs.HfPurchasepriceHistoryModal.open(record)
    },
    handleTax() {
      this.$refs.HandlePurchaseTaxModal.visible = true
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      params['isDelete'] = 0
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((record, index) => {
              record.priceFile = JSON.parse(record.priceFile)
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    deleteUploadedFile(item, index, id) {
      Modal.confirm({
        title: '确认删除',
        content: '是否删除已上传的文件?',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          let param = {
            fileUrl: item,
            fileKey: index,
            priceId: id
          }
          deleteAction(this.url.deleteUploadedFileUrl, param).then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              this.loadData()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    previewFile(fileUrl) {
      window.open(fileUrl, '_blank')
    },
    downloadFile(item) {
      fetch(item)
        .then(response => response.blob())
        .then(blob => {
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          let fileName = item.split('/')[item.split('/').length - 2]
          link.download = fileName
          link.click()
          link.addEventListener('click', function(e) {
            e.preventDefault()
            window.URL.revokeObjectURL(link.href)
          })
        })
        .catch(e => console.error('Download error:', e))
    },
    handleAutoInputCustom() {
      this.inputSupplier.loading = true
      getAction(this.url.autoInputCustomUrl, {}, { timeout: 0 })
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.inputSupplier.loading = false
        })
    },
    handleOpenBatchAdd() {
      this.$refs.HfBatchAddPurchasePriceRef.visible = true
    },
    handleBatchAddOk() {
      this.loadData()
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
